﻿using Dapper;
using System;
using BCEntity.TMS.OrderTranstionRecord;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading.Tasks;
using BCCommon;
using BCCommon.TMS.Order;

namespace BCData.TMS.OrderTranstionRecord
{
	/// <summary>
	/// 订单流转记录
	/// </summary>
	public class OrderTranstionRecordData : IOrderTranstionRecordData
	{
		private readonly IDatabaseContext databaseContext;
		private const string QUERY_EXISTS = @"SELECT 1 FROM ordertranstionrecord";
		private const string QUERY = @"SELECT OrderTranstionRecordId,OrderId,OrderNo,TranstionTitle,TranstionStatus,CreateTime,CompleteTime FROM ordertranstionrecord";
		public OrderTranstionRecordData(IDatabaseContext databaseContext)
		{
			this.databaseContext = databaseContext;
		}
		#region 检查订单流转记录是否存在
		public async Task<bool> Exists(long orderTranstionRecordId)
		{
			string sql = string.Format(@"{0} WHERE OrderTranstionRecordId=?OrderTranstionRecordId", QUERY_EXISTS);
			DynamicParameters parameters = new DynamicParameters();
			parameters.Add("?OrderTranstionRecordId", orderTranstionRecordId, DbType.Int64);
			return await this.databaseContext.Master.ExecuteScalarAsync(sql, parameters) != null;
		}
		#endregion

		#region 添加订单流转记录
		public async Task<OrderTranstionRecordEntity> Add(OrderTranstionRecordEntity entity)
		{
			string sql = SqlCommands.GetInsertSql("ordertranstionrecord", new string[] { "OrderId", "OrderNo", "TranstionTitle", "TranstionStatus" });
			sql = string.Format("{0} {1} WHERE OrderTranstionRecordId=LAST_INSERT_ID();", sql, QUERY);
			DynamicParameters parameters = new DynamicParameters();
			parameters.Add("?OrderId", entity.OrderId, DbType.Int64, size: 20);
			parameters.Add("?OrderNo", entity.OrderNo?.Trim(), DbType.AnsiString, size: 50);
			parameters.Add("?TranstionTitle", entity.TranstionTitle?.Trim(), DbType.String);
			parameters.Add("?TranstionStatus", OrderTranstionStatus.Processing.ToString(), DbType.AnsiString, size: 30);
			return await this.databaseContext.Master.QueryFirstOrDefaultAsync<OrderTranstionRecordEntity>(sql, parameters, databaseContext.Transaction);

		}
		#endregion

		#region 修改订单流转记录
		public async Task<OrderTranstionRecordEntity> Update(OrderTranstionRecordEntity entity)
		{
			string sql = SqlCommands.GetUpdateSql("ordertranstionrecord", new string[] { "OrderId", "OrderNo", "TranstionTitle", "TranstionStatus" }, new string[] { "OrderTranstionRecordId" });
			sql = string.Format("{0} {1} WHERE OrderTranstionRecordId=?OrderTranstionRecordId;", sql, QUERY);
			DynamicParameters parameters = new DynamicParameters();
			parameters.Add("?OrderTranstionRecordId", entity.OrderTranstionRecordId, DbType.Int64, size: 20);
			parameters.Add("?OrderId", entity.OrderId, DbType.Int64, size: 20);
			parameters.Add("?OrderNo", entity.OrderNo?.Trim(), DbType.AnsiString, size: 50);
			parameters.Add("?TranstionTitle", entity.TranstionTitle?.Trim(), DbType.String);
			parameters.Add("?TranstionStatus", entity.TranstionStatus?.Trim(), DbType.AnsiString, size: 30);
			return await this.databaseContext.Master.QueryFirstOrDefaultAsync<OrderTranstionRecordEntity>(sql, parameters, databaseContext.Transaction);
		}
		public async Task<bool> UpdateComplete(long orderTranstionRecordId)
        {
			string sql = SqlCommands.GetUpdateSql("ordertranstionrecord", new string[] { "CompleteTime", "TranstionStatus" }, new string[] { "OrderTranstionRecordId" });

			DynamicParameters parameters = new DynamicParameters();
			parameters.Add("?OrderTranstionRecordId", orderTranstionRecordId, DbType.Int64, size: 20);
			parameters.Add("?TranstionStatus", OrderTranstionStatus.Done.ToString(), DbType.AnsiString, size: 30);
			parameters.Add("?CompleteTime", DateTime.Now, DbType.DateTime);
			return await this.databaseContext.Master.ExecuteAsync(sql, parameters, databaseContext.Transaction)>0;
		}

		#endregion

		#region 删除订单流转记录
		public async Task<bool> Delete(long orderTranstionRecordId)
		{
			string sql = @"DELETE FROM ordertranstionrecord WHERE OrderTranstionRecordId=?OrderTranstionRecordId";
			DynamicParameters parameters = new DynamicParameters();
			parameters.Add("?OrderTranstionRecordId", orderTranstionRecordId, DbType.Int64);
			return await this.databaseContext.Master.ExecuteAsync(sql, parameters, databaseContext.Transaction) > 0;
		}
		#endregion

		#region 获取订单流转记录
		public async Task<OrderTranstionRecordEntity> GetEntity(long orderTranstionRecordId)
		{
			string sql = string.Format(@"{0} WHERE OrderTranstionRecordId=?OrderTranstionRecordId", QUERY);
			DynamicParameters parameters = new DynamicParameters();
			parameters.Add("?OrderTranstionRecordId", orderTranstionRecordId, DbType.Int64);
			return await this.databaseContext.Master.QueryFirstOrDefaultAsync<OrderTranstionRecordEntity>(sql, parameters);
		}

		public async Task<OrderTranstionRecordEntity> GetProcessEntity(long orderId)
		{
			string sql = string.Format(@"{0} WHERE OrderId=?OrderId AND TranstionStatus='Processing' ORDER BY CreateTime DESC LIMIT 1", QUERY);
			DynamicParameters parameters = new DynamicParameters();
			parameters.Add("?OrderId", orderId, DbType.Int64);
			return await this.databaseContext.Master.QueryFirstOrDefaultAsync<OrderTranstionRecordEntity>(sql, parameters);
		}
		#endregion

		#region 获取订单流转记录列表
		public async Task<IEnumerable<OrderTranstionRecordEntity>> GetList(string orderNo)
		{
			string sql = string.Format("{0} WHERE OrderNo=?OrderNo", QUERY);
			DynamicParameters parameters = new DynamicParameters();
			parameters.Add("OrderNo", orderNo, DbType.AnsiString);
			return await this.databaseContext.Master.QueryAsync<OrderTranstionRecordEntity>(sql, parameters);
		}
		public async Task<IEnumerable<OrderTranstionRecordEntity>> GetList(long orderId)
		{
			string sql = string.Format("{0} WHERE OrderId=?OrderId", QUERY);
			DynamicParameters parameters = new DynamicParameters();
			parameters.Add("OrderId", orderId, DbType.Int64);
			return await this.databaseContext.Master.QueryAsync<OrderTranstionRecordEntity>(sql, parameters);
		}
		#endregion

		#region 获取订单流转记录分页
		public async Task<(IEnumerable<OrderTranstionRecordEntity>, int)> Query(DateTime? start, DateTime? end, string sortName, bool? ascending, int pageIndex, int pageSize)
		{
			List<string> wheres = new List<string>();
			DynamicParameters parameters = new DynamicParameters();

			if (start.HasValue && !end.HasValue)
			{
				wheres.Add("CreateTime>=?Start");
				parameters.Add("?Start", start.Value, DbType.DateTime);
			}
			else if (!start.HasValue && end.HasValue)
			{
				wheres.Add("CreateTime<=?End");
				parameters.Add("?End", end.Value, DbType.DateTime);
			}
			else if (start.HasValue && end.HasValue)
			{
				wheres.Add("CreateTime>=?Start AND CreateTime<=?End");
				parameters.Add("?Start", start.Value, DbType.DateTime);
				parameters.Add("?End", end.Value, DbType.DateTime);
			}
			string sql = string.Format(@"{0} {1} ORDER BY {4} {5} LIMIT {2},{3}; SELECT COUNT(1) FROM ordertranstionrecord {1}",
				  QUERY,
				  wheres.Count > 0 ? " WHERE " + string.Join(" AND ", wheres) : "",
				  (pageIndex == 0 ? 0 : pageIndex - 1) * pageSize,
				  pageSize,
				  string.IsNullOrWhiteSpace(sortName) ? "CreateTime" : sortName,
				  ascending.HasValue && ascending.Value ? "ASC" : "DESC");
			return await this.databaseContext.QueryMultipleAsync<OrderTranstionRecordEntity, int>(sql, parameters);
		}
        #endregion
    }
}



